<template>
  <div class="merchants-container">
    <!-- 头部区域 -->
    <PageHeader title="商户管理" subtitle="管理系统中所有商户的信息和状态">
      <template #actions>
        <button class="admin-btn admin-btn--primary" @click="openAddMerchantModal">
          <i class="fas fa-plus"></i> 新增商户
        </button>
<!--        <button class="admin-btn admin-btn&#45;&#45;outline admin-btn&#45;&#45;secondary">-->
<!--          <i class="fas fa-download"></i> 导出数据-->
<!--        </button>-->
      </template>
    </PageHeader>

    <!-- 搜索筛选区域 -->
    <div class="admin-card admin-mb--lg">
      <div class="admin-flex admin-flex--between admin-flex--wrap admin-flex--gap-md">
        <div class="search-box">
          <el-input v-model="queryInfo.shop_title" class="w-50 m-2" placeholder="请输入店铺名称" :suffix-icon="'Search'"
            size="large" clearable @clear="resetList" @change="resetList" />
        </div>

        <div class="admin-flex admin-flex--gap-md admin-flex--wrap">
          <div class="filter-item">
            <label class="admin-form__label">商户类型</label>
            <Select v-model="queryInfo.shop_class" mode="api" is-flat labelKey="type_name" valueKey="id" isLevele
              apiUrl="api/admin/typeAddAndEdit" @change="resetList" />
          </div>

          <div class="filter-item">
            <label class="admin-form__label">状态</label>
            <el-select v-model="queryInfo.status" @change="resetList" placeholder="请选择商户状态" size="large">
              <el-option v-for="item in shopStatus" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>

          <button class="admin-btn admin-btn--outline admin-btn--info" @click="resetFilters">
            <i class="fas fa-redo"></i> 重置筛选
          </button>
        </div>
      </div>
    </div>

    <!-- 商户卡片区域 -->
    <div class="merchants-content">
      <LoadingState v-if="loading" text="加载商户数据中..." :overlay="false" size="large" />

      <EmptyState v-else-if="shopList.length === 0" title="未找到符合条件的商户" description="尝试调整您的搜索条件或查看所有商户"
        icon="fas fa-store-alt-slash">
        <template #action>
          <button class="admin-btn admin-btn--secondary" @click="resetFilters">重置筛选条件</button>
        </template>
      </EmptyState>

      <div v-else class="merchant-card-grid">
        <div v-for="merchant in shopList" :key="merchant.id" class="merchant-card-container">
          <MerchantCard :merchant="merchant" @edit="handleEditMerchant" @manage-products="handleManageProducts"
            @toggle-status="handleToggleStatus" @view-details="handleViewDetails" @choose-cover="handleChooseCover"
            @choose-banner="handleChooseBanner" @delete="handleDeleteMerchant" />
        </div>
      </div>

      <!-- 分页控件 -->
      <div class="admin-pagination" v-if="filteredMerchants.length > pageSize">
        <button class="admin-pagination__btn" :disabled="queryInfo.page === 1" @click="handleLastPage">
          <i class="fas fa-chevron-left"></i>
        </button>

        <span class="admin-pagination__info">{{ queryInfo.page }} / {{ queryInfo.pagesTotal }}</span>

        <button class="admin-pagination__btn" :disabled="queryInfo.page === queryInfo.pagesTotal"
          @click="handleNextPage">
          <i class="fas fa-chevron-right"></i>
        </button>
      </div>
    </div>

    <!-- 操作结果提示 -->
    <div v-if="actionMessage" class="action-message" :class="actionMessageType">
      <i :class="actionMessageIcon"></i>
      {{ actionMessage }}
    </div>

    <!-- 商户表单模态框 -->
    <MerchantFormModal :shopStatus="shopStatus" v-model:visible="formVisible" :merchant-data="editingMerchant"
      :is-edit="isEditMode" @submit="handleFormSubmit" @closeModal="editingMerchant = {}" />

    <!-- 确认对话框 -->
    <ConfirmDialog v-model="confirmDialogVisible" :title="confirmDialogOptions.title"
      :message="confirmDialogOptions.message" :type="confirmDialogOptions.type"
      :confirm-text="confirmDialogOptions.confirmText" @confirm="confirmDialogOptions.onConfirm" />

    <ChooseCoverModal ref="chooseCoverModalRef" mode="radio" @confirm="reloadList" />

    <ChooseBannerModal ref="chooseBannerModalRef" mode="multiple" @confirm="reloadList" />
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import Select from '@/components/admin/Select.vue'
import { generateMerchantData } from '@/utils/adminMock'
import { Calendar, Search } from '@element-plus/icons-vue'
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import MerchantCard from '@/components/admin/merchants/MerchantCard.vue'
import MerchantFormModal from '@/components/admin/merchants/MerchantFormModal.vue'
import PageHeader from '@/components/admin/common/PageHeader.vue'
import EmptyState from '@/components/admin/common/EmptyState.vue'
import LoadingState from '@/components/admin/common/LoadingState.vue'
import StatusTag from '@/components/admin/common/StatusTag.vue'
import ConfirmDialog from '@/components/admin/common/ConfirmDialog.vue'
import { GetShopList, deleteShopApi, UserAddAndEdit, SetShopEditApi, SetShopAddApi } from '@/api/index'
import MerchantTypeSelect from '@/components/admin/merchants/MerchantTypeSelect.vue'
import ChooseCoverModal from '@/components/admin/merchants/ChooseCoverModal.vue'
import ChooseBannerModal from '@/components/admin/merchants/ChooseBannerModal.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 搜索和筛选状态
const searchQuery = ref('')
const loading = ref(true)
const actionMessage = ref('')
const currentPage = ref(1)
const pageSize = 8

// 商户数据
const merchants = ref<any[]>([])
const selectedMerchants = ref<any[]>([])

// 表单控制
const formVisible = ref(false)
const editingMerchant = ref<any>({})
const isEditMode = ref(false)

// 分类列表
const categories = [
  '餐厅',
  '咖啡厅',
  '快餐',
  '火锅',
  '烧烤',
  '西餐',
  '日料',
  '甜品',
  '饮品',
  '小吃',
]

// 过滤器
const filters = ref({
  category: '',
  status: '',
})

// 添加确认对话框状态
const confirmDialogVisible = ref(false)
const confirmDialogOptions = ref({
  title: '',
  message: '',
  type: 'danger' as 'danger' | 'warning' | 'info',
  confirmText: '确认',
  onConfirm: () => { },
})

// 操作消息类型和图标
const actionMessageType = ref('success')
const actionMessageIcon = computed(() => {
  switch (actionMessageType.value) {
    case 'success':
      return 'fas fa-check-circle'
    case 'error':
      return 'fas fa-times-circle'
    case 'warning':
      return 'fas fa-exclamation-circle'
    default:
      return 'fas fa-info-circle'
  }
})

// 初始加载数据
onMounted(async () => {
  try {
    // 模拟API加载延迟
    setTimeout(() => {
      // 在实际应用中，这里会调用API获取数据
      merchants.value = generateMerchantData(28)
      loading.value = false
    }, 800)
  } catch (error) {
    console.error('加载商户数据失败:', error)
    loading.value = false
  }
})

// 筛选数据
const filteredMerchants = computed(() => {
  let result = [...merchants.value]

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter((merchant) => merchant.name.toLowerCase().includes(query))
  }

  // 应用过滤条件
  if (filters.value.category) {
    result = result.filter((merchant) => merchant.category === filters.value.category)
  }

  if (filters.value.status) {
    result = result.filter((merchant) => merchant.status === filters.value.status)
  }

  return result
})

// 处理编辑商户
function handleEditMerchant(merchant: any) {
  Object.assign(editingMerchant.value, {
    ...merchant,
    user_name: merchant.shop_title,
    user_cover: '',
    remarks: merchant.shop_describe,
    shop_class: merchant.shop_class,
    classId: '',
    status: merchant.status,
    address: merchant.address,
  })

  console.log(11111111111, editingMerchant.value);

  isEditMode.value = true
  formVisible.value = true
}

// 处理管理产品
function handleManageProducts(merchant: any) {
  router.push(`/admin/merchants/${merchant.user_id}/products`)
  showActionMessage(`正在前往管理商户产品: ${merchant.name}`, 'success')
}

// 处理查看详情
function handleViewDetails(merchant: any) {
  router.push(`/admin/merchants/${merchant.id}`)
  showActionMessage(`正在查看商户详情: ${merchant.name}`, 'success')
}

const chooseCoverModalRef = ref()

const handleChooseCover = (record) => {
  chooseCoverModalRef.value.open({
    data: {
      shopId: record.user_id
    }
  })
}

const chooseBannerModalRef = ref()

const handleChooseBanner = (record) => {
  chooseBannerModalRef.value.open({
    data: {
      shopId: record.user_id,
      ids: record.user_banner
    }
  })
}

// 处理状态切换
function handleToggleStatus(merchant: any) {
  const newStatus = merchant.status === 'active' ? 'inactive' : 'active'
  const statusText = newStatus === 'active' ? '启用' : '禁用'

  confirmDialogOptions.value = {
    title: `确认${statusText}商户`,
    message: `您确定要${statusText}商户 "${merchant.name}" 吗？${newStatus === 'inactive' ? '禁用后该商户将无法在前台显示。' : ''}`,
    type: newStatus === 'active' ? 'info' : 'warning',
    confirmText: statusText,
    onConfirm: () => {
      // 在实际应用中，这里会调用API更新状态
      const index = merchants.value.findIndex((m) => m.id === merchant.id)
      if (index !== -1) {
        merchants.value[index] = { ...merchant, status: newStatus }
      }

      showActionMessage(`已${statusText}商户: ${merchant.name}`, 'success')
      confirmDialogVisible.value = false
    },
  }
  confirmDialogVisible.value = true
}

// 显示操作提示消息，增加类型参数
function showActionMessage(message: string, type: 'success' | 'error' | 'warning' = 'success') {
  actionMessage.value = message
  actionMessageType.value = type
  setTimeout(() => {
    actionMessage.value = ''
  }, 3000)
}

// 打开添加商户模态框
function openAddMerchantModal() {
  editingMerchant.value = {
    id: '',
    name: '',
    logo: '',
    category: '',
    address: '',
    status: '',
    phone: '',
    email: '',
    joinDate: new Date().toISOString().split('T')[0],
  }
  isEditMode.value = false
  formVisible.value = true
}

// 处理表单提交
function handleFormSubmit(merchantData: any) {
  if (isEditMode.value) {
    // 更新现有商户
    // const index = merchants.value.findIndex((m) => m.id === merchantData.id)
    // if (index !== -1) {
    //   merchants.value[index] = { ...merchantData }
    //   showActionMessage(`商户 ${merchantData.name} 已更新`, 'success')
    // }

    submitUserFormRequest(merchantData.id ? 'edit' : 'add', merchantData)

  } else {
    // 添加新商户
    submitUserFormRequest(merchantData.id ? 'edit' : 'add', merchantData)
  }
}


// 提交用户信息请求
const submitUserFormRequest = async (type, merchantData) => {
  try {
    let res

    // 处理数据为后端所需的
    merchantData.shop_cover_list = merchantData.shop_cover_list.split(',')

    merchantData.shop_banner_list = merchantData.shop_banner_list.split(',')

    if (type == 'add') {
      res = SetShopAddApi(merchantData).then(red => {
        if (red.code === 200) {
          showActionMessage(`商户 ${merchantData.user_name} 已创建`, 'success')
		  setTimeout(() => {
		    formVisible.value = false
		  }, 1000)
          //formVisible.value = false
          return
        }
        showActionMessage(`创建失败`, 'error')
        ElMessage({
          type:"success",
          message:'创建成功'
        })
        return
      }).catch(err => {
        console.error('接口失败', err)
      })
    } else {
      res = SetShopEditApi(merchantData).then(red => {
        if (red.code === 200) {
          showActionMessage(`商户 ${merchantData.user_name} 已修改`, 'success')
		  setTimeout(() => {
		    formVisible.value = false
		  }, 1000)
          //formVisible.value = false
          location.reload();
          return
        }
        ElMessage({
          type: "success",
          message: '编辑成功'
        })
        showActionMessage(`修改失败`, 'error')
        return
      }).catch(err => {
        console.error('接口失败', err)
      })
    }
		setTimeout(() => {
		   reloadList()
		  }, 2000)

    return

    // if (type == 'add') {
    // 	res = await SetShopAddApi(merchantData)
    // 	if (res.code == 200) {
    // 		showActionMessage(`商户 ${merchantData.user_name} 已创建`, 'success')
    // 		formVisible.value = false
    // 	} else {
    // 		showActionMessage(`创建失败`, 'error')
    // 	}
    // 	return
    // } else {
    // 	res = SetShopEditApi(merchantData)
    // 	if (res.code == 200) {
    // 		showActionMessage(`商户 ${merchantData.user_name} 已修改`, 'success')
    // 		formVisible.value = false
    // 	} else {
    // 		showActionMessage(`修改失败`, 'error')
    // 	}
    // 	return
    // }
  } catch (err) { }
}
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}
// --------------------------
const handleDeleteMerchant = (record) => {
  ElMessageBox.confirm(`确认删除商户${record.shop_title}`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await deleteShopApi({ id: record.id })

      ElMessage({
        type: 'success',
        message: '删除成功'
      })

      reloadList()
    } catch (error) {
      ElMessage({
        type: 'error',
        message: error.msg
      })
    }
  })
}

// 商户状态
const shopStatus = [
  {
    label: '禁用',
    value: 0,
  },
  {
    label: '启用',
    value: 1,
  },
]

// 列表请求参数
const queryInfo = reactive({
  shop_title: '',
  status: '',
  page: 1,
  limit: 10,
  pagesTotal: 0,
})

// 上一页点击事件
const handleLastPage = () => {
  queryInfo.page--

  getShopListRequest()
}

// 下一页点击事件
const handleNextPage = () => {
  queryInfo.page++

  getShopListRequest()
}

// 商户列表
const shopList = ref([])

const handleSearch = () => {
  queryInfo.page = 1

  getShopListRequest()
}

const reloadList = () => {
  nextTick(() => {
    getShopListRequest()
  })
}

const resetList = () => {
  queryInfo.page = 1

  nextTick(() => {
    getShopListRequest()
  })
}

// 重置过滤器
function resetFilters() {
  Object.assign(queryInfo, {
    shop_title: '',
    status: '',
    page: 1,
    limit: 10,
    pagesTotal: 0,
  })

  resetList()
}

// 获取商户列表数据
const getShopListRequest = async () => {
  try {
    const { data: res } = await GetShopList(queryInfo)

    shopList.value = res.data

    queryInfo.pagesTotal = Math.ceil(res.total / queryInfo.limit)
  } catch (err) {
    console.log('getShopListRequest', err)
  }
}

getShopListRequest()
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';
@import '@/assets/styles/mixins.scss';

.merchants-container {
  padding: $spacing-md;
  position: relative;
}

.merchant-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: $spacing-lg;
  margin-bottom: $spacing-xl;
}

.search-box {
  position: relative;
  width: 100%;
  max-width: 300px;

  .search-icon {
    position: absolute;
    right: $spacing-md;
    top: 50%;
    transform: translateY(-50%);
    color: $gray-500;
    pointer-events: none;
  }
}

.filter-item {
  min-width: 180px;
}

.action-message {
  position: fixed;
  bottom: $spacing-xl;
  right: $spacing-xl;
  padding: $spacing-sm $spacing-lg;
  border-radius: $border-radius-lg;
  background-color: $white;
  box-shadow: $shadow-lg;
  display: flex;
  align-items: center;
  gap: $spacing-sm;
  z-index: $z-index-tooltip;
  transition: all 0.3s ease;
  animation: slideIn 0.3s forwards;

  &.success {
    border-left: 4px solid $success;

    i {
      color: $success;
    }
  }

  &.error {
    border-left: 4px solid $danger;

    i {
      color: $danger;
    }
  }

  &.warning {
    border-left: 4px solid $warning;

    i {
      color: $warning;
    }
  }

  i {
    font-size: $font-size-lg;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(30px);
  }

  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@media (max-width: $breakpoint-md) {
  .merchant-card-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media (max-width: $breakpoint-sm) {
  .merchant-card-grid {
    grid-template-columns: 1fr;
  }
}
</style>
